<?php

require_once 'MainPageWidget.php';
class StatsWidget extends MainPageWidget
{
	public $title = 'Статистика';
	public $from = 'community';
	public $tdis = array();
	public $tdi_list = array();
	public $root_checked = false;

	public function Render() {
		$community_oid = $this->acl_assistant->acl_data['comity_oid'];

		$tdi_string = join(',', $this->tdi_list);

		// кол-во статей
		if ( '' != $tdi_string ) {
			$sql = "select count(*) as `count` from store_objects o " .
			" left join store_class_allfeed a on a.oid = o.oid " .
			" where a.community_oid = {$community_oid} and o.is_deleted = 0 " .
			" and a.tdi_oid in ({$tdi_string})";

			$results = $this->store->db->QueryOne($sql);

			if ( !empty($results) && isset($results['count']) ) {
				$items_count = $results['count'];
			} else {
				$items_count = 0;
			}
		} else {
			$ql = "select count objects where allfeed.community_oid==:0 and allfeed.is_deleted==0";
			$results = $this->store->find( $ql, array($community_oid) )->next();
			$items_count = $results->data['count'];
		}

		// кол-во комментов
		$sql = "
			SELECT count(*) as comments_count
			FROM store_class_comment cm
			left join store_objects so on so.oid = cm.oid
			INNER JOIN store_class_allfeed af on cm.item_oid = af.oid and af.community_oid = ".$this->acl_assistant->acl_data['comity_oid']."
			INNER JOIN t_acl_tree tat ON tat.id_object = cm.oid AND tat.is_deleted = 0
			WHERE cm.is_deleted = 0 and so.is_deleted = 0";

		if ( '' != $tdi_string ) {
			$sql .= " and af.tdi_oid in ({$tdi_string})";
		}

		$result = $this->ctx->db->QueryOne($sql);

		//$users_count = $this->acl_assistant->getMembersCount($community_oid);

		$sql = "select count(*) as `count` from store_class_member m " .
		" left join store_objects o on o.oid = m.oid " .
		" where m.community_oid = {$community_oid} and o.is_deleted = 0 ";

		$users = $this->ctx->db->QueryOne($sql);

		$content['item_count'] = $items_count;
		$content['comments_count'] = $result['comments_count'];
		$content['user_count'] = $this->getParam("user_count", $users['count']);
		$content['title'] = $this->getParam("title", "Статистика");

		$this->content = $content;
		return $this;
	}

	public function settingsForm() {
		if ( !isset($this->params) || !isset($this->params['title']) ) {
			$this->params['title'] = $this->title;
		}

		$this->tdis = $this->getTdiList( $this->acl_assistant->acl_data['comity_oid'] );

		foreach ($this->tdis as $index=>$tdi) {
			foreach ($this->tdi_list as $present) {
				if ( $present == $tdi['oid'] ) {
					$this->tdis[$index]['checked'] = true;
				} else  if ( 0 == $present ) {
					$this->root_checked = true;
				}
			}
		}
	}

	public function setParams( $params ) {
		foreach ( $params as $key=>$val ) {
			if ( isset($this->$key) ) {
				$this->$key = $val;
			}
		}
	}
}